package cn.sciento.transfer.infra.datasource.ddl.sqlserver.dto;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

public class IndexEntity {
  public static final String INDEX_NAME = "index_name";
  
  public static final String INDEX_KEYS = "index_keys";
  
  public static final String INDEX_DESCRIPTION = "index_description";
  
  public static final String SPLID = ",";
  
  private String indexName;
  
  private String indexColumns;
  
  private Integer indexType;
  
  public static List<IndexEntity> build(List<Map<String, Object>> indexMapList) {
    List<IndexEntity> indexEntityList = new ArrayList<>();
    if (CollectionUtils.isEmpty(indexMapList))
      return indexEntityList; 
    for (Map<String, Object> indexMap : indexMapList) {
      IndexEntity indexEntity = new IndexEntity();
      indexEntity.setIndexName((String)indexMap.get("index_name"));
      String indexDescription = (String)indexMap.get("index_description");
      if (indexDescription.contains("clustered") && indexDescription.contains("primary key")) {
        indexEntity.setIndexType(Integer.valueOf(2));
      } else if (indexDescription.contains("nonclustered") && indexDescription.contains("unique key")) {
        indexEntity.setIndexType(Integer.valueOf(1));
      } else {
        indexEntity.setIndexType(Integer.valueOf(0));
      } 
      String indexKeys = (String)indexMap.get("index_keys");
      StringBuilder indexColumnsBuilder = new StringBuilder();
      indexColumnsBuilder.append("(");
      if (StringUtils.isNotEmpty(indexKeys)) {
        String[] split = indexKeys.split(",");
        List<String> indexColumns = Arrays.asList(split);
        for (String indexColumn : indexColumns) {
          indexColumnsBuilder.append("[");
          indexColumnsBuilder.append(indexColumn.trim());
          indexColumnsBuilder.append("]");
          indexColumnsBuilder.append(",");
        } 
      } 
      indexColumnsBuilder.deleteCharAt(indexColumnsBuilder.lastIndexOf(","));
      indexColumnsBuilder.append(")");
      indexEntity.setIndexColumns(indexColumnsBuilder.toString());
      indexEntityList.add(indexEntity);
    } 
    return indexEntityList;
  }
  
  public String getIndexName() {
    return this.indexName;
  }
  
  public void setIndexName(String indexName) {
    this.indexName = indexName;
  }
  
  public String getIndexColumns() {
    return this.indexColumns;
  }
  
  public void setIndexColumns(String indexColumns) {
    this.indexColumns = indexColumns;
  }
  
  public Integer getIndexType() {
    return this.indexType;
  }
  
  public void setIndexType(Integer indexType) {
    this.indexType = indexType;
  }
}
